package com.mainbo.core.activemq.parser;

import com.mainbo.core.common.constant.Const;
import com.mainbo.core.activemq.model.PfMessage;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @author moshang
 * @date 2020-03-01
 **/
public final class MessageMarshallers {

    private static Map<Object, Marshaller<? extends PfMessage<Serializable>>> cachedResponseParsers = new HashMap<>();

    private static Map<Object, Marshaller<? extends PfMessage<Serializable>>> cachedJSONResponseParsers = new HashMap<>();

    /**
     * get marshaller by class
     * @param c class
     * @return marshaller
     */
    public static <T extends PfMessage<Serializable>> Marshaller<T> getMarshaller(
            Class<T> c) {
        return getMarshaller(c, Const.TP_JSON);
    }

    /**
     * get marshaller by class of format type.
     * @param c class
     * @param formatType format type
     * @return marshaller
     */
    @SuppressWarnings("unchecked")
    public static <T extends PfMessage<Serializable>> Marshaller<T> getMarshaller(
            Class<T> c, String formatType) {
        Marshaller<T> rp;
        if (Const.TP_JSON.equalsIgnoreCase(formatType)) {
            rp = (Marshaller<T>) cachedJSONResponseParsers.get(c);
            if (rp == null) {
                rp = new JsonMessageParser<T>(c);
                cachedJSONResponseParsers.put(c, rp);
            }
        } else {
            rp = (Marshaller<T>) cachedResponseParsers.get(c);
            if (rp == null) {
                rp = new JAXBMessageParser<T>(c);
                cachedResponseParsers.put(c, rp);
            }
        }

        return rp;
    }

}
